<template>
  <div class="filter">
    <div class="uploadBtn" v-if="localTypeUnit == 1">
      <el-select
        v-model="typeUnit"
        class="m-2"
        placeholder="请选择上传单位"
        size="large"
        style="width: 160px"
        :disabled="true"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <div class="uploadBtn">
      <el-date-picker
        v-model="dateStartTime"
        type="date"
        size="large"
        :disabled-date="disabledDate1"
      />
    </div>
    <div class="uploadBtn" style="line-height: 38rem">至</div>
    <div class="uploadBtn">
      <el-date-picker
        v-model="dateEndTime"
        type="date"
        size="large"
        :disabled-date="disabledDate2"
      />
    </div>
    <!-- <div class="uploadBtn">
            <el-date-picker v-model="timeDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" size="large" />
        </div> -->
    <div class="uploadBtn">
      <el-button size="large" type="primary" @click="search">查询</el-button>
    </div>
  </div>
  <el-table
    :data="getValues"
    :show-header="false"
    border
    :span-method="objectSpanMethod"
    ref="tableList"
    size="small"
    :height="hHeight + 'px'"
  >
    <el-table-column prop="title" label="" :width="60" fixed="" align="center">
      <template #default="scope">
        <span>{{ identifyResultList[scope.$index].title }}</span>
      </template>
    </el-table-column>
    <el-table-column
      v-for="(item, index) in getHeaders"
      :key="index"
      :prop="item"
      :fixed="index == 0"
      :width="index < 1 ? 80 : 60"
      align="center"
    >
      <template #default="scope">
        <span v-if="index == 0 || scope.$index == 0">{{
          scope.row[item]
        }}</span>
        <el-input
          v-else-if="index > 0"
          v-model="scope.row[item]"
          size="small"
          @blur="blurFn(index, scope.$index, scope.row[item])"
          @focus="focusFn(index, scope.$index)"
          :disabled="isNoEdit()"
        />
        <!-- {{ index }}{{ scope.$index }} {{ scope.row[item] }} -->
      </template>
    </el-table-column>
  </el-table>
  <div class="uploadBtn" style="margin-bottom: 0">
    <el-button
      @click="submitEdit"
      size="large"
      type="primary"
      style="width: 212px; margin-top: 40rem"
      >提交</el-button
    >
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch } from "vue";
import moment from "moment";
import dataListHttp from "@/https/dataList.js";
import ChartLineBar from "../charts/ChartLineBar.vue";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { ElMessage, ElMessageBox } from "element-plus";
const dateStartTime = ref(moment().startOf("month").format("YYYY-MM-DD"));
const dateEndTime = ref(moment().format("YYYY-MM-DD"));
const disabledDate1 = ref((time) => {
  return time.getTime() > Date.now();
});
const disabledDate2 = ref((time) => {
  return (
    time.getTime() < moment(dateStartTime.value) || time.getTime() > Date.now()
  );
});
const emits = defineEmits(["submitEditEmit"]);
// const timeDate = ref([moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')])
const currentYear = ref(moment().format("YYYY"));
const localTypeUnit = ref(Storage.localGet("depId"));
const typeUnit = ref("2");
const username = ref(Storage.localGet("username"));
const options = ref([
  // { label: '全部', value: '1' },
  { label: "星沙厂", value: "2" },
  { label: "城西厂", value: "3" },
  { label: "城北厂", value: "4" },
  { label: "城南厂", value: "5" },
]);
const hHeight = ref(0);
const wWidth = ref(0);
const tableItemWidth = ref(0);
const option = ref({});
const chartTypeModel = ref("ssIn");
const chartTypeList = ref([
  { label: "处理水量", value: "treatedWaterQuantity", idx: 0 },
  { label: "水温", value: "waterTemperature", idx: 1 },
  { label: "PH进水", value: "phIn", idx: 2 },
  { label: "PH出水", value: "phOut", idx: 3 },
  { label: "SS进水", value: "ssIn", idx: 4 },
  { label: "SS出水", value: "ssOut", idx: 5 },
  { label: "COD进水", value: "codIn", idx: 6 },
  { label: "COD出水", value: "codOut", idx: 7 },
  { label: "BOD5进水", value: "bodIn", idx: 8 },
  { label: "BOD5出水", value: "bodOut", idx: 9 },
  { label: "TN进水", value: "tnIn", idx: 10 },
  { label: "TN出水", value: "tnOut", idx: 11 },
  { label: "NH3-N进水", value: "nhNIn", idx: 12 },
  { label: "NH3-N出水", value: "nhNOut", idx: 13 },
  { label: "TP进水", value: "tpIn", idx: 14 },
  { label: "TP出水", value: "tpOut", idx: 15 },
  { label: "粪大肠菌群", value: "cufOut", idx: 16 },
]);
const chartTypeItem = ref([
  {
    type: "line",
    code: "treatedWaterQuantity",
    name: "处理水量",
    linerColor: ["#b5bfd8", "#b5bfd8"],
  },
]);
const chartType = ref([
  {
    type: "line",
    code: "treatedWaterQuantity",
    name: "处理水量",
    linerColor: ["#b5bfd8", "#b5bfd8"],
  },
  {
    type: "line",
    code: "waterTemperature",
    name: "水温",
    linerColor: ["#3ea7ea", "#3ea7ea"],
  },
  {
    type: "line",
    code: "phIn",
    name: "PH进水",
    linerColor: ["#bdf5e8", "#bdf5e8"],
  },
  {
    type: "line",
    code: "phOut",
    name: "PH出水",
    linerColor: ["#9cf7b4", "#9cf7b4"],
  },
  {
    type: "line",
    code: "ssIn",
    name: "SS进水",
    linerColor: ["#76da91", "#76da91"],
  },
  {
    type: "line",
    code: "ssOut",
    name: "SS出水",
    linerColor: ["#63b2ee", "#63b2ee"],
  },
  {
    type: "line",
    code: "codIn",
    name: "COD进水",
    linerColor: ["#f89588", "#f89588"],
  },
  {
    type: "line",
    code: "codOut",
    name: "COD出水",
    linerColor: ["#f8cb7f", "#f8cb7f"],
  },
  {
    type: "line",
    code: "bodIn",
    name: "BOD5进水",
    linerColor: ["#7898e1", "#7898e1"],
  },
  {
    type: "line",
    code: "bodOut",
    name: "BOD5出水",
    linerColor: ["#7cd6cf", "#7cd6cf"],
  },
  {
    type: "line",
    code: "tnIn",
    name: "TN进水",
    linerColor: ["#eddd86", "#eddd86"],
  },
  {
    type: "line",
    code: "tnOut",
    name: "TN出水",
    linerColor: ["#efa666", "#efa666"],
  },
  {
    type: "line",
    code: "nhNIn",
    name: "N进水",
    linerColor: ["#63b2ee", "#63b2ee"],
  },
  {
    type: "line",
    code: "nhNOut",
    name: "NH3-N出水",
    linerColor: ["#9987ce", "#9987ce"],
  },
  {
    type: "line",
    code: "tpIn",
    name: "TP进水",
    linerColor: ["#9192ab", "#9192ab"],
  },
  {
    type: "line",
    code: "tpOut",
    name: "TP出水",
    linerColor: ["#76da91", "#76da91"],
  },
  {
    type: "line",
    code: "cufOut",
    name: "粪大肠菌群",
    linerColor: ["#89caf2", "#89caf2"],
  },
]);
const chartTypeModelChange = (item, label) => {
  console.log(item, label);
  let idx = chartTypeList.value.findIndex((t) => {
    return t.value == item;
  });
  console.log(idx);
  chartTypeItem.value[0] = chartType.value[idx];
};
const unit = ref(["单位:mg/L"]);
const chartList = ref([]);
const uploadInitDataList = ref([]);
const uploadDataList = ref([]);

onMounted(() => {
  // nextTick(() => {
  hHeight.value = document.documentElement.clientHeight - 420;
  wWidth.value = document.documentElement.clientWidth - 296;
  // })
  initTable();
});
const initDate = ref([]);
const initTable = () => {
  initDate.value = [];
  resultList.value = [];
  uploadDataList.value = [];
  uploadInitDataList.value = [];
  // 计算选中日期相隔天数
  let startTime = moment(dateStartTime.value);
  let endTime = moment(dateEndTime.value);
  let tableDay = endTime.diff(startTime, "day");
  if (tableDay <= 31) {
    tableItemWidth.value = wWidth.value / (tableDay + 10);
  } else {
    tableItemWidth.value = wWidth.value / 41;
  }
  for (let i = 0; i <= tableDay; i++) {
    initDate.value.push(
      moment(dateStartTime.value).add(i, "day").format("MM-DD")
    );
    resultList.value.push({
      entryDate: moment(dateStartTime.value).add(i, "day").format("YYYYMMDD"),
      depId: typeUnit.value,
      date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
      entryDate: moment(dateStartTime.value).add(i, "day").format("YYYYMMDD"),
      do1: "",
      do2: "",
      do3: "",
      do4: "",
      do5: "",
      do6: "",
      do7: "",
      mlss1: "",
      mlss2: "",
      mlss3: "",
      mlss4: "",
      mlss5: "",
      mlss6: "",
      mlss7: "",
      mlvss1: "",
      mlvss2: "",
      mlvss3: "",
      mlvss4: "",
      mlvss5: "",
      mlvss6: "",
      mlvss7: "",
      sv1: "",
      sv2: "",
      sv3: "",
      sv4: "",
      sv5: "",
      sv6: "",
      sv7: "",
      svi1: "",
      svi2: "",
      svi3: "",
      svi4: "",
      svi5: "",
      svi6: "",
      svi7: "",
      containWater1: "",
      containWater2: "",
      containWater3: "",
    });
  }

  getWaterDateList();
};
const getWaterDateList = () => {
  let params = {
    depId: typeUnit.value,
    // "depId": 4,
    startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
    endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
    auditStatus: "1",
  };
  dataListHttp.queryCraft(params).then((res) => {
    console.log(res);
    for (let key in res.data.data) {
      if (initDate.value.includes(key)) {
        let idx = initDate.value.findIndex((item) => {
          return item === key;
        });
        res.data.data[key].entryDate = resultList.value[idx].entryDate;
        res.data.data[key].depId = typeUnit.value;
        resultList.value[idx] = res.data.data[key];
      }
    }
    uploadDataList.value = JSON.parse(JSON.stringify(resultList.value));
    uploadInitDataList.value = JSON.parse(JSON.stringify(resultList.value));
    chartList.value = resultList.value;

    // getWaterOtherDateList()
  });
};

const identifyResultList = ref([
  { title: "日期", label: "rq" },
  { title: "DO(mg/L)", label: "do1" },
  { title: "DO(mg/L)", label: "do2" },
  { title: "DO(mg/L)", label: "do3" },
  { title: "DO(mg/L)", label: "do4" },
  { title: "DO(mg/L)", label: "do5" },
  { title: "DO(mg/L)", label: "do6" },
  { title: "DO(mg/L)", label: "do7" },
  { title: "MLSS(mg/L)", label: "mlss1" },
  { title: "MLSS(mg/L)", label: "mlss2" },
  { title: "MLSS(mg/L)", label: "mlss3" },
  { title: "MLSS(mg/L)", label: "mlss4" },
  { title: "MLSS(mg/L)", label: "mlss5" },
  { title: "MLSS(mg/L)", label: "mlss6" },
  { title: "MLSS(mg/L)", label: "mlss7" },
  { title: "SV30(%)", label: "sv1" },
  { title: "SV30(%)", label: "sv2" },
  { title: "SV30(%)", label: "sv3" },
  { title: "SV30(%)", label: "sv4" },
  { title: "SV30(%)", label: "sv5" },
  { title: "SV30(%)", label: "sv6" },
  { title: "SV30(%)", label: "sv7" },
  { title: "SVI(mL/g)", label: "svi1" },
  { title: "SVI(mL/g)", label: "svi2" },
  { title: "SVI(mL/g)", label: "svi3" },
  { title: "SVI(mL/g)", label: "svi4" },
  { title: "SVI(mL/g)", label: "svi5" },
  { title: "SVI(mL/g)", label: "svi6" },
  { title: "SVI(mL/g)", label: "svi7" },
  { title: "MLVSS(mg/L)", label: "mlvss1" },
  { title: "MLVSS(mg/L)", label: "mlvss2" },
  { title: "MLVSS(mg/L)", label: "mlvss3" },
  { title: "MLVSS(mg/L)", label: "mlvss4" },
  { title: "MLVSS(mg/L)", label: "mlvss5" },
  { title: "MLVSS(mg/L)", label: "mlvss6" },
  { title: "MLVSS(mg/L)", label: "mlvss7" },
  { title: "污泥含水率(%)", label: "containWater1" },
  { title: "污泥含水率(%)", label: "containWater2" },
  { title: "污泥含水率9%)", label: "containWater3" },
]);
const resultList = ref([]);
const headersList = ref([
  {
    prop: "date",
    label: "日期",
  },
  {
    prop: "do1",
    label: "氧化沟东",
  },
  {
    prop: "do2",
    label: "氧化沟西",
  },
  {
    prop: "do3",
    label: "cass",
  },
  {
    prop: "do4",
    label: "A2/O东",
  },
  {
    prop: "do5",
    label: "A2/O西",
  },
  {
    prop: "do6",
    label: "四期南沟",
  },
  {
    prop: "do7",
    label: "四期北沟",
  },
  {
    prop: "mlss1",
    label: "氧化沟东",
  },
  {
    prop: "mlss2",
    label: "氧化沟西",
  },
  {
    prop: "mlss3",
    label: "cass",
  },
  {
    prop: "mlss4",
    label: "A2/O东",
  },
  {
    prop: "mlss5",
    label: "A2/O西",
  },
  {
    prop: "mlss6",
    label: "四期南沟",
  },
  {
    prop: "mlss7",
    label: "四期北沟",
  },
  {
    prop: "sv1",
    label: "氧化沟东",
  },
  {
    prop: "sv2",
    label: "氧化沟西",
  },
  {
    prop: "sv3",
    label: "cass",
  },
  {
    prop: "sv4",
    label: "A2/O东",
  },
  {
    prop: "sv5",
    label: "A2/O西",
  },
  {
    prop: "sv6",
    label: "四期南沟",
  },
  {
    prop: "sv7",
    label: "四期北沟",
  },
  {
    prop: "svi1",
    label: "氧化沟东",
  },
  {
    prop: "svi2",
    label: "氧化沟西",
  },
  {
    prop: "svi3",
    label: "cass",
  },
  {
    prop: "svi4",
    label: "A2/O东",
  },
  {
    prop: "svi5",
    label: "A2/O西",
  },
  {
    prop: "svi6",
    label: "四期南沟",
  },
  {
    prop: "svi7",
    label: "四期北沟",
  },
  {
    prop: "mlvss1",
    label: "氧化沟东",
  },
  {
    prop: "mlvss2",
    label: "氧化沟西",
  },
  {
    prop: "mlvss3",
    label: "cass",
  },
  {
    prop: "mlvss4",
    label: "A2/O东",
  },
  {
    prop: "mlvss5",
    label: "A2/O西",
  },
  {
    prop: "mlvss6",
    label: "四期南沟",
  },
  {
    prop: "mlvss7",
    label: "四期北沟",
  },
  {
    prop: "containWater1",
    label: "北厂区污泥脱水间",
  },
  {
    prop: "containWater2",
    label: "南厂区污泥脱水间",
  },
  {
    prop: "containWater3",
    label: "四期脱水间",
  },
]);
const getUnitTypeName = computed(() => {
  return typeUnit.value == 1
    ? "总公司"
    : typeUnit.value == 2
    ? "星沙厂"
    : typeUnit.value == 3
    ? "城西厂"
    : typeUnit.value == 4
    ? "城北厂"
    : typeUnit.value == 4
    ? "城南厂"
    : "";
});
const getHeaders = computed(() => {
  return uploadDataList.value.reduce(
    (pre, cur, index) => pre.concat(`value${index}`),
    ["title"]
  );
});
const getValues = computed(() => {
  return headersList.value.map((item) => {
    return uploadDataList.value.reduce(
      (pre, cur, index) =>
        Object.assign(pre, { ["value" + index]: cur[item.prop] }),
      { title: item.label }
    );
  });
});
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  let len = uploadDataList.value.length;
  if (rowIndex === 0) {
    if (columnIndex === 0) {
      return [1, 2];
    } else if (columnIndex === 1) {
      return [0, 0];
    }
  }
  if (columnIndex === 0) {
    if (rowIndex === 1) {
      return {
        rowspan: 7,
        colspan: 1,
      };
    } else if (rowIndex === 8) {
      return {
        rowspan: 7,
        colspan: 1,
      };
    } else if (rowIndex === 15) {
      return {
        rowspan: 7,
        colspan: 1,
      };
    } else if (rowIndex === 22) {
      return {
        rowspan: 7,
        colspan: 1,
      };
    } else if (rowIndex === 29) {
      return {
        rowspan: 7,
        colspan: 1,
      };
    } else if (rowIndex === 36) {
      return {
        rowspan: 3,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};
const search = () => {
  initTable();
};

const blurFn = (row, column, item) => {
  console.log(row, column);
  uploadDataList.value[row - 1][identifyResultList.value[column].label] = item;
  console.log(uploadDataList.value);
};

const focusFn = (row, column) => {
  console.log(row, column);
  window.addEventListener(
    "paste",
    (event) => {
      event = event || window.event;
      const clipdata = event.clipboardData || window.clipboardData;
      const value = clipdata.getData("text/plain");
      console.log("...................", value);

      let clipboardList = value.split("\r\n");
      clipboardList.forEach((item, ind) => {
        let itemList = item.split("\t");
        clipboardList[ind] = itemList;
      });
      setTimeout(() => {
        console.log("1111", clipboardList);
        clipboardList.forEach((item, ind) => {
          item.forEach((n, m) => {
            n = n.replace(/\s+/g, "");
            n = n.replace(/(\r\n|\n|\r)/gm, "");
            if (row - 1 + m < uploadDataList.value.length) {
              console.log("////////////////////", n, m);

              uploadDataList.value[row - 1 + m][
                identifyResultList.value[column + ind].label
              ] = n;
            }
          });
        });
      });
    },
    { once: true }
  );
};
const isNoEdit = () => {
  return false;
};

watch(
  uploadInitDataList,
  (newVal, oldVal) => {
    console.log("11111", newVal);
  },
  { deep: true }
);
watch(
  uploadDataList,
  (newVal, oldVal) => {
    console.log("222", newVal);
  },
  { deep: true }
);
const submitEdit = () => {
  setTimeout(() => {
    let compare1 = {
      obj: uploadInitDataList.value,
    };
    let compare2 = {
      obj: uploadDataList.value,
    };
    console.log(uploadInitDataList.value, uploadDataList.value);
    if (JSON.stringify(compare1) == JSON.stringify(compare2)) {
      ElMessage({
        message: "没有检测到数据修改",
        type: "warning",
      });
    } else {
      ElMessageBox.alert(`确认提交当前修改的数据吗？`, "提交修改", {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: "确认",
        callback: (action) => {
          uploadDataList.value.forEach((item) => {
            item.date = item.entryDate;
          });
          let params = {
            dailyPOList: uploadDataList.value,
            username: username.value,
          };
          dataListHttp.entryDailyCraft(params).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
              ElMessage({
                message: "提交成功",
                type: "success",
              });
              initTable();
              emits("submitEditEmit");
            } else {
              ElMessage({
                message: "提交失败,请重新提交",
                type: "error",
              });
            }
          });
        },
      });
    }
  }, 100);
};
const resetEdit = () => {
  initTable();
};
const exportDataList = () => {
  let params = {
    // "depId": 4,
    depId: typeUnit.value,
    startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
    endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
  };
  dataListHttp.exportAssay(params).then((response) => {
    console.log(response);
    const content = response.data;
    const blob = new Blob([content], { type: "application/ms-excel" });
    let fileName = `化验数据.xls`;
    if ("download" in document.createElement("a")) {
      // 非IE下载
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
  });
};
</script>

<style scoped lang="less">
.waterYield {
  background: #fff;
  height: 100%;
}

.filter {
  display: flex;
  align-items: center;
}

.uploadBtn {
  text-align: left;
  margin-bottom: 40rem;
  margin-right: 20rem;
}

.chart {
  margin-top: 60px;
}

.unit {
  text-align: right;
  font-size: 14px;
  line-height: 2;
  padding-right: 40px;
  margin-top: -20px;
}
</style>
